import { AfterContentInit, Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { MemberVo } from 'src/app/model/member-vo';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { LetterService } from 'src/app/services/letter.service';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { environment } from 'src/environments/environment';
import { concatMap, map } from 'rxjs/operators';
import { LetterInboxVo } from 'src/app/model/letter-inbox-vo';
import { HttpErrorResponse } from '@angular/common/http';
import { UtilService } from 'src/app/services/util.service';
import { LetterInboxNoticeVo } from 'src/app/model/letter-inbox-notice-vo';
import { ScrollPageResult } from 'src/app/model/scroll-page-result';

@Component({
  selector: 'app-inbox-page',
  templateUrl: './inbox-page.component.html',
  styles: [``]
})
export class InboxPageComponent implements OnInit, AfterContentInit {
  public errorMessage: string = '';
  public curMember: MemberVo | null;
  //当前页码值
  public page: number = 1;
  //每页显示的数量
  public pageSize: number = 20;
  public items: LetterInboxVo[] = [];
  public hasNext: boolean = false;
  //当前的URL,用以浏览历史:window.history.pushState
  private url: string = '#';
  private unreadSet: LetterInboxNoticeVo[] = [];

  /**
   * 会员的收件箱
   * @param title 
   * @param location 
   * @param router 
   * @param activatedRoute 
   * @param letterService 
   * @param memberStorage 
   * @param util 
   * @param btnNaviSharedService 
   */
  constructor(
    private title: Title,
    private location: Location,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private letterService: LetterService,
    private memberStorage: MemberStorageService,
    private util: UtilService,
    private btnNaviSharedService: BtnNaviSharedService) {
    this.btnNaviSharedService.active(true);//需要全局的导航
    this.curMember = this.memberStorage.get();
    this.activatedRoute.url.pipe(map(s => s.join('/'))).subscribe(res => {
      this.url = '/' + res;
    });
  }

  ngAfterContentInit(): void {
  }

  ngOnInit(): void {
    if (null === this.curMember) {
      this.router.navigate(['/member/login']);
    }
    this.title.setTitle("收件箱");
    this.page = +(this.activatedRoute.snapshot.queryParamMap.get('p') ?? 1);
    this.pageSize = +(this.activatedRoute.snapshot.queryParamMap.get('s') ?? environment.pageSize);
    this.getDate();
  }

  //加载指定页码的数据
  private getDate(): void {
    this.letterService.getInbox(this.curMember?.id ?? 0, this.page, this.pageSize).pipe(map(epr => {
      return { result: epr.result, hasNext: epr.total > epr.page * epr.size } as ScrollPageResult<LetterInboxVo>;
    })).pipe(
      concatMap(
        (spr: ScrollPageResult<LetterInboxVo>) => {
          //有哪些发件人?
          const senderIds: number[] = spr.result.map(liv => liv.sender);
          return this.letterService.getUnreadCollectSize(this.curMember?.id ?? 0, senderIds).pipe(map(lins => {
            return { notices: lins, data: spr };
          }))
        })).subscribe({
          next: response => {
            const rs: { notices: LetterInboxNoticeVo[], data: ScrollPageResult<LetterInboxVo> } = response;
            //未读消息集合
            this.unreadSet = rs.notices;
            //计算结果
            this.items = rs.data.result;
            this.hasNext = rs.data.hasNext;
          },
          error: err => {
            if (err instanceof HttpErrorResponse) {
              if (err.error instanceof ErrorEvent) {
                this.errorMessage = err.error.message;
              } else {
                this.errorMessage = err.error;
              }
            } else if (err instanceof Error) {
              this.errorMessage = err.message;
            } else { this.errorMessage = err; }
            console.log('[Inbox-Page]view error ' + this.errorMessage);
          },
          complete: () => { console.log('[Inbox-Page]view Completed'); }
        });
  }

  //返回发件人未读的消息
  public getUnReadMessageSize(sender: number): string {
    let linv: LetterInboxNoticeVo | undefined = this.unreadSet.find(ele => ele.sender === sender);
    if (!linv) { //不存在未读的消息
      return '';
    }
    return linv.count + '';
  }

  //底部的点击加载更多,后期会替换为:自动加载
  public anymore(event: Event): void {
    this.page += 1;
    this.getDate();
    this.location.replaceState(this.url, 'p=' + this.page + '&s=' + this.pageSize);
  }

  //标记为已读
  //:/message/read/all?member=-1&direction=2
  public readed(event: Event): void {
    this.letterService.readAll(this.curMember?.id ?? 0, 2, -1).subscribe({
      next: response => {
        this.util.alertSuccess('标记成功');
      },
      error: err => {
        let em: string = '';
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            em = err.error.message;
          } else {
            em = (err.status === 417) ? '操作失败' : err.error;
          }
        } else if (err instanceof Error) {
          em = err.message;
        } else { em = err; }
        this.util.alertError(em);
        console.log('[Inbox-CTL]readed error ' + em);
      },
      complete: () => { console.log('[Inbox-CTL]readed Completed'); }
    });
  }
}
